﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using XDesigner.Writer;
using XDesigner.Writer.Controls;
using XDesigner.Writer.Commands;
using XDesigner.Writer.Dom;
using XDesigner.Writer.Html;
using XDesigner.Drawing;
using XDesigner.Writer.Data;
using XDesigner.Writer.Security;

namespace XDesigner.Writer.Test
{
    /// <summary>
    /// Demo of XDesigner.Writer
    /// </summary>
    public partial class frmTextUseCommand : Form
    {
        public frmTextUseCommand()
        {
            InitializeComponent();
            //myEditControl.Enabled = false;
            myEditControl.ServerObject = new ServerObjectSample(this);
            myEditControl.DoubleBuffering = false;
            //myEditControl.ViewMode = Printing.PageViewMode.Normal;
            //myEditControl.Document.Options.EditOptions.AutoEditElementValue = true;
            //myEditControl.IsAdministrator = true;
            //myEditControl.Readonly = true;
            myEditControl.KeyPress += new KeyPressEventHandler(myEditControl_KeyPress);
            myEditControl.DocumentControler = new MyDocumentControler();
            //myEditControl.IsAdministrator = true;
            //myEditControl.DocumentControler.DataFilter = new MyDataFilter();
        }

        private AppStartOptions _StartOptions = new AppStartOptions();

        public AppStartOptions StartOptions
        {
            get { return _StartOptions; }
            set { _StartOptions = value; }
        }
        
        private void frmTextUseCommand_Load(object sender, EventArgs e)
        {
            myEditControl.Font = new Font(System.Windows.Forms.Control.DefaultFont.Name, 12 );
            if (_StartOptions == null)
            {
                _StartOptions = new AppStartOptions();
            }
            myEditControl.DoubleBuffering = _StartOptions.DoubleBuffering;
            // Add service object instacne
            myEditControl.AppHost.Services.AddService(
                typeof(IInputFieldListItemProvider),
                MyDataProvider.Instance);

            myEditControl.AppHost.Services.AddService(
                typeof(XDesigner.Writer.Dom.FilterValueEventHandler ),
                new FilterValueEventHandler( MyFilterData));

            myEditControl.CommandControler = myCommandControler;
            myCommandControler.Start();
            myEditControl.DocumentOptions = new DocumentOptions();
            if (_StartOptions.EnablePermissionControl)
            {
                // Enable permission control
                myEditControl.DocumentOptions.SecurityOptions.EnableLogicDelete = true;
                myEditControl.DocumentOptions.SecurityOptions.EnablePermission = true;
                myEditControl.DocumentOptions.SecurityOptions.ShowLogicDeletedContent = true;
                myEditControl.DocumentOptions.SecurityOptions.ShowPermissionMark = true;
                mPermissionConfig.Enabled = true;
                mLogin.Enabled = true;
                 
            }
            else
            {
                // Without permission control
                myEditControl.DocumentOptions.SecurityOptions.EnableLogicDelete = false;
                myEditControl.DocumentOptions.SecurityOptions.EnablePermission = false;
                myEditControl.DocumentOptions.SecurityOptions.ShowLogicDeletedContent = false;
                myEditControl.DocumentOptions.SecurityOptions.ShowPermissionMark = false;
                mPermissionConfig.Enabled = false ;
                mLogin.Enabled = false;
            }
            this.myEditControl_DocumentLoad(null, null);
            //myEditControl.ExecuteCommand(StandardCommandNames.FileNew, false, null);
        }


        private void MyFilterData(object sender, FilterValueEventArgs args)
        {
            if (args.Type == InputValueType.Dom)
            {
                XTextElementList sourceElements = (XTextElementList)args.Value;
                foreach (XTextElement element in sourceElements)
                {
                    if (element is XTextCheckBoxElement)
                    {
                        ((XTextCheckBoxElement)element).EditorChecked = false;
                    }
                    if (element is XTextInputFieldElement)
                    {
                        XTextInputFieldElement field = (XTextInputFieldElement)element;
                        field.EditorTextExt = "aaaaaaaaabbb";
                        field.InnerValue = null;
                        DocumentContentStyle style = new DocumentContentStyle();
                        style.DisableDefaultValue = true;
                        style.BackgroundColor = Color.Transparent;
                        style.Color = Color.Blue;
                        field.EditorSetContentStyle(style, false);
                    }
                }
                args.Value = sourceElements;
            }
        }

        /// <summary>
        /// Handle after load document
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void myEditControl_DocumentLoad(object sender, EventArgs e)
        {
            if (myEditControl.DocumentOptions.SecurityOptions.EnablePermission)
            {
                // if enable permission 
                if (myEditControl.Document != null && _StartOptions.LoginInfo != null)
                {
                    // User logon , add current user info to document.
                    myEditControl.UserLogin(_StartOptions.LoginInfo , false );
                }
            }
        }

        public class MyDocumentControler : XDesigner.Writer.Dom.DocumentControler
        {
            public override bool CanDelete(XTextElement element, DomAccessFlags flags)
            {

                //if (element is XTextInputFieldElement)
                //{
                //    return false;
                //}
                return base.CanDelete(element, flags);
            }
        }


        void myEditControl_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r')
            {
                XTextInputFieldElement field = ( XTextInputFieldElement ) myEditControl.GetCurrentElement(typeof(XTextInputFieldElement));
                if (field != null && field.MultiParagraph == false )
                {
                    if (myEditControl.CurrentElement != field.StartElement)
                    {
                        XTextInputFieldElement nextField = (XTextInputFieldElement)myEditControl.Document.GetNextElement(
                            field, typeof(XTextInputFieldElement));
                        if (nextField != null)
                        {
                            nextField.Focus();
                            e.Handled = true;
                        }
                    }
                }
            }
        }
         

        /// <summary>
        /// Demo of server object in document
        /// </summary>
        public class ServerObjectSample
        {
            public ServerObjectSample(frmTextUseCommand frm)
            {
                _Form = frm;
            }

            private frmTextUseCommand _Form = null;
            public frmTextUseCommand Form
            {
                get
                {
                    return _Form;
                }
            }

            public string FormTitle
            {
                get
                {
                    return _Form.Text;
                }
            }

            public string AppPath
            {
                get
                {
                    return Application.StartupPath;
                }
            }

            private string _Name = "Zhang san";

            public string Name
            {
                get { return _Name; }
                set { _Name = value; }
            }

            private DateTime _Birthday = new DateTime( 1990 , 1 , 1);

            public DateTime Birthday
            {
                get { return _Birthday; }
                set { _Birthday = value; }
            }

            private string _Nation = "China";

            public string Nation
            {
                get { return _Nation; }
                set { _Nation = value; }
            }
        }

        private void menuClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        protected override void OnClosing(CancelEventArgs e)
        {
            base.OnClosing(e);
        }

        private void menuOpenXMLDemo_Click(object sender, EventArgs e)
        {
            HandleCommand(MyCommandNames.OpenXMLDemo);
        }

        private void menuOpenRTFDemo_Click(object sender, EventArgs e)
        {
            HandleCommand(MyCommandNames.OpenRTFDemo);
        }

        private void mOpenFormViewDemo_Click(object sender, EventArgs e)
        {
            HandleCommand(MyCommandNames.OpenFormViewDemo);
        }

        /// <summary>
        /// Current file name.
        /// </summary>
        private string strFileName = null;
         
        /// <summary>
        /// Handle commands
        /// </summary>
        /// <param name="Command">command name</param>
        public void HandleCommand(string Command)
        {
            if (Command == null)
                return;
            Command = Command.Trim();
            try
            {
                switch (Command)
                {
                    case MyCommandNames.OpenXMLDemo:
                        if (QuerySave())
                        {
                            this.strFileName = null;
                            this.Cursor = System.Windows.Forms.Cursors.WaitCursor;
                            string name = System.Threading.Thread.CurrentThread.CurrentUICulture.Name;
                            name = name.Trim().ToLower();
                            name = "XDesigner.Writer.Test.DemoFile.demo.xml";
                            using (System.IO.Stream stream = this.GetType().Assembly.GetManifestResourceStream(name))
                            {
                                myEditControl.LoadDocument(stream, FileFormat.XML);
                                stream.Close();
                            }
                            myEditControl.ExecuteCommand("FormViewMode", false, false);
                            this.Cursor = System.Windows.Forms.Cursors.Default;
                        }
                        break;
                    case MyCommandNames.OpenFormViewDemo :
                        if (QuerySave())
                        {
                            this.strFileName = null;
                            this.Cursor = System.Windows.Forms.Cursors.WaitCursor;
                            string name = System.Threading.Thread.CurrentThread.CurrentUICulture.Name;
                            name = name.Trim().ToLower();
                            name = "XDesigner.Writer.Test.DemoFile.FormViewModeDemo.xml";
                            using (System.IO.Stream stream = this.GetType().Assembly.GetManifestResourceStream(name))
                            {
                                myEditControl.LoadDocument(stream, FileFormat.XML);
                                stream.Close();
                            }
                            myEditControl.ExecuteCommand("FormViewMode", false, true);
                            this.Cursor = System.Windows.Forms.Cursors.Default;
                        }
                        break;
                    case MyCommandNames.OpenRTFDemo:
                        if (QuerySave())
                        {
                            this.strFileName = null;
                            this.Cursor = System.Windows.Forms.Cursors.WaitCursor;
                            string name = System.Threading.Thread.CurrentThread.CurrentUICulture.Name;
                            name = name.Trim().ToLower();
                            name = "XDesigner.Writer.Test.DemoFile.demo.rtf";
                            using (System.IO.Stream stream = this.GetType().Assembly.GetManifestResourceStream(name))
                            {
                                this.myEditControl.LoadDocument(stream, FileFormat.RTF);
                                stream.Close();
                            }
                            myEditControl.ExecuteCommand("FormViewMode", false, false);
                            this.Cursor = System.Windows.Forms.Cursors.Default;
                        }
                        break;
                    case MyCommandNames.New:
                        // new document
                        if (QuerySave())
                        {
                            this.myEditControl.ClearContent();
                            //myEditControl.Document.HeaderString = GetResourceString("_TEXTDEMO");
                            //myEditControl.Document.HeaderHeight = 100 ;
                            //myEditControl.Document.HeaderFont = new XFontValue( System.Windows.Forms.Control.DefaultFont.Name , 12 );
                            //myEditControl.Document.FooterString = "[%pageindex%]/[%pagecount%]";
                            //myEditControl.Document.FooterHeight = 100 ;
                            //myEditControl.Document.FooterFont = new XFontValue( System.Windows.Forms.Control.DefaultFont.Name , 12 );
                            myEditControl.RefreshDocument();
                            strFileName = null;
                        }
                        break;
                    case MyCommandNames.Open:
                        // open document
                        if (QuerySave())
                        {
                            using (System.Windows.Forms.OpenFileDialog dlg = new OpenFileDialog())
                            {
                                dlg.Filter = ResourceStrings._SAVEFILTER;
                                dlg.CheckFileExists = true;
                                if (dlg.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
                                {
                                    this.Update();
                                    this.OpenDocument(dlg.FileName);
                                }
                            }
                        }
                        break;
                    case MyCommandNames.Save:
                        // save document
                        SaveDocument(strFileName);
                        break;
                    case MyCommandNames.SaveAs:
                        // save document as
                        SaveDocument(null);
                        break;
                     
                    case MyCommandNames.Link:
                        // set link
                        {
                            myEditControl.Document.BeginLogUndo();
                            using (dlgLink dlg = new dlgLink())
                            {
                                dlg.InputText = myEditControl.CurrentStyle.Link;
                                XTextElementList list = myEditControl.Document.Bookmarks;
                                foreach (XTextBookmark mark in list)
                                {
                                    dlg.Bookmarks.Add(mark.Name);
                                }
                                if (dlg.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
                                {
                                    DocumentContentStyle style = new DocumentContentStyle();
                                    style.DisableDefaultValue = true;
                                    style.Link = dlg.InputText;
                                    myEditControl.Selection.SetElementStyle(style);
                                }
                            }
                            myEditControl.Document.EndLogUndo();
                        }
                        break;
                     
                    //case MyCommandNames.ShowBookmark:
                    //    // show or hide bookmark
                    //    myEditControl.Document.ViewOptions.ShowBookmark = !myEditControl.Document.ViewOptions.ShowBookmark;
                    //    //menuShowBookmark.Checked = myEditControl.Document.ShowBookmark ;
                    //    this.mShowBookmark.Checked = myEditControl.Document.ViewOptions.ShowBookmark;
                    //    myEditControl.Invalidate();
                    //    break;
                    //case MyCommandNames.WordCount:
                    //    this.ShowWordCount();
                    //    break;
                     
                    default:
#if DEBUG
                        this.Alert("Bad command:" + Command);
#endif
                        break;
                }
            }
            catch (Exception ext)
            {
                this.Alert( ResourceStrings._EXEERR  + ext.ToString());
                this.Status = ResourceStrings._EXEERR + ext.Message;
            }
            this.UpdateFormText();
        }


        /// <summary>
        /// Show a message box
        /// </summary>
        /// <param name="msg">message text</param>
        private void Alert(string msg)
        {
            MessageBox.Show(this, msg, this.Text);
        }


        /// <summary>
        /// get or set main status text
        /// </summary>
        private string Status
        {
            get { return this.lblStatus.Text; }
            set { this.lblStatus.Text = value; this.Update(); }
        }


        /// <summary>
        /// open special file
        /// </summary>
        /// <param name="fileName">file name ,it can be xml,rtf or txt file</param>
        private void OpenDocument(string fileName)
        {
            try
            {
                this.Cursor = System.Windows.Forms.Cursors.WaitCursor;
                string name = fileName.Trim().ToLower();
                FileFormat style = FileFormat.XML;
                if (name.EndsWith(".xml"))
                {
                    style = FileFormat.XML;
                }
                else if (name.EndsWith(".rtf"))
                {
                    style = FileFormat.RTF;
                }
                else if (name.EndsWith(".txt"))
                {
                    style = FileFormat.Text;
                }
                this.Status = ResourceStrings._OPENING + fileName;
                this.myEditControl.LoadDocument(fileName, style);
                this.strFileName = fileName;
                this.Status = ResourceStrings._OPENED + fileName;
                UpdateFormText();
            }
            catch (Exception ext)
            {
                this.Alert(string.Format(
                    ResourceStrings._OPENERR,
                    fileName,
                    ext.ToString()));
                this.Status = string.Format(
                    ResourceStrings._OPENERR,
                    fileName,
                    ext.Message);
            }
            this.Cursor = System.Windows.Forms.Cursors.Default;
        }

        /// <summary>
        /// save document
        /// </summary>
        /// <param name="name">file name</param>
        /// <returns></returns>
        private bool SaveDocument(string name)
        {
            if (name == null)
            {
                using (System.Windows.Forms.SaveFileDialog dlg = new SaveFileDialog())
                {
                    dlg.Filter = ResourceStrings._SAVEFILTER;
                    dlg.CheckPathExists = true;
                    if (dlg.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
                        name = dlg.FileName;
                    else
                        return false;
                }
                this.Update();
            }

            FileFormat style = FileFormat.XML;

            try
            {
                string name2 = name.Trim().ToLower();
                if (name2.EndsWith(".rtf"))
                    style = FileFormat.RTF;
                else
                    style = FileFormat.XML;
                this.Status = ResourceStrings._SAVING + name;
                if (this.myEditControl.SaveDocument(name, style))
                {
                    strFileName = name;
                }
                this.Status = ResourceStrings._SAVED + name;
                UpdateFormText();
                return true;
            }
            catch (Exception ext)
            {
                string txt = string.Format(ResourceStrings._SAVEERR, name, ext.ToString());
                this.Alert(txt);
                this.Status = txt;
                return false;
            }
        }


        /// <summary>
        /// If document modified , show query message
        /// </summary>
        /// <returns>If return true , then can go no ; return false , cancel operation</returns>
        private bool QuerySave()
        {
            if (this.myEditControl.Document.Modified)
            {
                System.Windows.Forms.DialogResult result = MessageBox.Show(
                    this,
                    ResourceStrings._QUERYSAVE,
                    this.Text,
                    MessageBoxButtons.YesNoCancel,
                    MessageBoxIcon.Question);
                if (result == System.Windows.Forms.DialogResult.Yes)
                {
                    if (SaveDocument(strFileName) == false)
                        return false;
                }
                else if (result == System.Windows.Forms.DialogResult.No)
                    return true;
                else if (result == System.Windows.Forms.DialogResult.Cancel)
                    return false;
            }
            return true;
        }

        private FlagXTextRangeProvider provider = new FlagXTextRangeProvider();

        /// <summary>
        /// handle element hover event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void myEditControl_HoverElementChanged(object sender, EventArgs e)
        {
            provider.Document = myEditControl.Document;
            provider.Prefix = '{';
            provider.Endfix = '}';
            XTextRange range = provider.GetRange(myEditControl.HoverElement);
            if (range != null)
            {
                this.myEditControl.HighlightRange = new HighlightInfo(range);

            }
            else
            {
                this.myEditControl.HighlightRange = null;
            }
        }

        /// <summary>
        /// Handle selection changed event in editor control
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void myEditControl_SelectionChanged(object sender, EventArgs e)
        {
            //XTextFieldElement field = (XTextFieldElement)myEditControl.Document.CurrentField;
            //field.EditorTextExt = "bbb";

            provider.Document = myEditControl.Document;
            provider.Prefix = '{';
            provider.Endfix = '}';
            XTextRange range = provider.GetRange(myEditControl.CurrentElement);
            if (range != null)
            {
                myEditControl.HighlightRange = new HighlightInfo(range);
            }
            else
            {
                myEditControl.HighlightRange = null;
            }


            XTextLine line = myEditControl.Document.CurrentContentElement.CurrentLine;
            if (line != null && line.OwnerPage != null)
            {
                string txt =
                    string.Format( ResourceStrings._LINE ,
                    Convert.ToString(line.OwnerPage.PageIndex),
                    Convert.ToString(myEditControl.CurrentLineIndexInPage ),
                    Convert.ToString(myEditControl.CurrentColumnIndex));
                if (myEditControl.Selection.Length != 0)
                {
                    txt = txt + string.Format(
                        ResourceStrings._SELECTELEMENTS,
                        Math.Abs(myEditControl.Selection.Length));
                }
                this.lblPosition.Text = txt;
            }
            UpdateFormText();
        }

        private void UpdateFormText()
        {
            string text = "XDesigner.Writer ";
            if (this.myEditControl.Document.FileName != null)
            {
                text =myEditControl.Document.FileName + " - " + text  ;
            }
            if (myEditControl.Document.Modified)
            {
                text = text + " *";
            }
            this.Text = text;
        }

        private void frmTextUseCommand_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (QuerySave() == false)
            {
                e.Cancel = true;
            }
        }

        private void mTest_Click(object sender, EventArgs e)
        {
            
        }


        private void mTestInsertField_Click(object sender, EventArgs e)
        {
            XTextInputFieldElementProperties property = new XTextInputFieldElementProperties();
            property.FieldSettings = new InputFieldSettings();
            property.FieldSettings.EditStyle = InputFieldEditStyle.DropdownList;
            property.InitalizeText = "测试文本ABC";
            property.Name = "COUNTRY";
            property.BackgroundText = "Please select country";
            property.FieldSettings.MultiSelect = false ;
            property.FieldSettings.EnableCustomListItems = true;
            property.Attributes = new XAttributeList();
            property.Attributes.SetValue("Insert time", DateTime.Now.ToLongDateString());
            XTextInputFieldElement newField = (XTextInputFieldElement)myEditControl.ExecuteCommand("InsertInputField", true, property);
            if (newField != null)
            {
                System.Console.WriteLine(newField.ToString());
            }
        }


        private void mTestInsertMedic_Click(object sender, EventArgs e)
        {
            XTextInputFieldElementProperties property = new XTextInputFieldElementProperties();
            property.FieldSettings = new InputFieldSettings();
            property.FieldSettings.EditStyle = InputFieldEditStyle.DropdownList;
            property.Name = "DOCEX";
            property.BackgroundText = "Docex";
            property.FieldSettings.MultiSelect = false ;
            property.FieldSettings.EnableCustomListItems = true;
            property.Attributes = new XAttributeList();
            property.Attributes.SetValue("Insert Time", DateTime.Now.ToLongDateString());
            myEditControl.ExecuteCommand("InsertInputField", true, property);
        }


        private void mTestInsertImage_Click(object sender, EventArgs e)
        {
            System.Drawing.Image img = Image.FromFile(System.IO.Path.Combine(Application.StartupPath, "About.jpg"));
            myEditControl.ExecuteCommand("InsertImage", false, img); return;
        }

        private void mTestInsertString_Click(object sender, EventArgs e)
        {
            myEditControl.ExecuteCommand("InsertString", false, "abc");
        }

        private void mTestInsertRTF_Click(object sender, EventArgs e)
        {
            myEditControl.ExecuteCommand("InsertRTF", false, @"{\rtf1\ansi\ansicpg936\deff0\deflang1033\deflangfe2052{\fonttbl{\f0\fnil\fcharset134 \'cb\'ce\'cc\'e5;}}
{\colortbl ;\red255\green0\blue0;}
{\*\generator Msftedit 5.41.21.2510;}{\info{\horzdoc}{\*\lchars ([\'7b\'a1\'a4\'a1\'ae\'a1\'b0\'a1\'b4\'a1\'b6\'a1\'b8\'a1\'ba\'a1\'be\'a1\'b2\'a1\'bc\'a3\'a8\'a3\'ae\'a3\'db\'a3\'fb\'a1\'ea\'a3\'a4}{\*\fchars !),.:\'3b?]\'7d\'a1\'a7\'a1\'a4\'a1\'a6\'a1\'a5\'a8\'44\'a1\'ac\'a1\'af\'a1\'b1\'a1\'ad\'a1\'c3\'a1\'a2\'a1\'a3\'a1\'a8\'a1\'a9\'a1\'b5\'a1\'b7\'a1\'b9\'a1\'bb\'a1\'bf\'a1\'b3\'a1\'bd\'a3\'a1\'a3\'a2\'a3\'a7\'a3\'a9\'a3\'ac\'a3\'ae\'a3\'ba\'a3\'bb\'a3\'bf\'a3\'dd\'a3\'e0\'a3\'fc\'a3\'fd\'a1\'ab\'a1\'e9}}
\viewkind4\uc1\pard\sa200\sl276\slmult1\lang2052\f0\fs22 1\cf1 2\cf0 3\par
}");
        }

        private void mTestInsertXML_Click(object sender, EventArgs e)
        {

            myEditControl.XMLText = @"<?xml version='1.0'?>
<XTextDocument xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema'>
  <XElements>
    <Element xsi:type='XTextBody'>
      <XElements>
        <Element xsi:type='XString'>
          <Text>111</Text>
        </Element>
        <Element xsi:type='XString' StyleIndex='0'>
          <Text>111</Text>
        </Element>
        <Element xsi:type='XString' StyleIndex='1'>
          <Text>11</Text>
        </Element>
        <Element xsi:type='XString' StyleIndex='2'>
          <Text>1</Text>
        </Element>
        <Element xsi:type='XString'>
          <Text>11</Text>
        </Element>
        <Element xsi:type='XParagraphFlag' />
      </XElements>
    </Element>
    <Element xsi:type='XTextHeader'>
      <XElements>
        <Element xsi:type='XParagraphFlag' />
      </XElements>
    </Element>
    <Element xsi:type='XTextFooter'>
      <XElements>
        <Element xsi:type='XParagraphFlag' />
      </XElements>
    </Element>
  </XElements>
  <Info>
    <CreationTime>2012-03-29T15:47:51.1032576+08:00</CreationTime>
    <LastModifiedTime>2012-03-29T15:47:51.1042577+08:00</LastModifiedTime>
    <LastPrintTime>1980-01-01T00:00:00</LastPrintTime>
    <Operator>XDesigner.Writer Version:1.0.1111.28434</Operator>
  </Info>
  <DefaultFont>
    <Size>12</Size>
  </DefaultFont>
  <ContentStyles>
    <Default>
      <FontName>宋体</FontName>
      <FontSize>12</FontSize>
    </Default>
    <Styles>
      <Style Index='0'>
        <Bold>true</Bold>
      </Style>
      <Style Index='1'>
        <FontSize>24</FontSize>
        <Bold>true</Bold>
      </Style>
      <Style Index='2'>
        <FontSize>24</FontSize>
      </Style>
    </Styles>
  </ContentStyles>
  <DocumentGraphicsUnit>Document</DocumentGraphicsUnit>
  <PageSettings>
    <DesignerPaperWidth>0</DesignerPaperWidth>
    <DesignerPaperHeight>0</DesignerPaperHeight>
  </PageSettings>
  <CustomerParameters />
</XTextDocument>";
        }

        private void mTestUpdateData_Click(object sender, EventArgs e)
        {
            XTextInputFieldElement field = (XTextInputFieldElement)myEditControl.GetCurrentElement(typeof(XTextInputFieldElement));
            field.EditorTextExt = DateTime.Now.ToString();
            return;
            //XTextElementList xTextElementList =  this.myEditControl.Document.GetSpecifyElements(typeof(XTextInputFieldElement));
            //myEditControl.IsAdministrator = true;
            //foreach (XTextFieldElement xTextInputFieldElement in xTextElementList)
            //{
            //    if (xTextInputFieldElement.Parent is XTextInputFieldElement || xTextInputFieldElement.Parent is XTextCheckBoxElement)
            //    {
            //        myEditControl.ExecuteCommand(StandardCommandNames.DeleteField, false, xTextInputFieldElement);
            //        //xTextInputFieldElement.EditorDelete(true);
            //    }
            //}
            //return;


            using (dlgProperty dlg = new dlgProperty())
            {
                dlg.InstanceToShow = myEditControl.ServerObject;
                dlg.Text = "This is values before update";
                dlg.ShowDialog(this);
                int result = this.myEditControl.WriteDataSource();
                if (result == 0)
                {
                    MessageBox.Show("No changed");
                }
                else
                {
                    dlg.Text = "This is values after update，modified " + result + " parts";
                    dlg.InstanceToShow = myEditControl.ServerObject;
                    dlg.ShowDialog(this);
                }
            }
        }

        private void mXML2RTF_Click(object sender, EventArgs e)
        {
            MessageBox.Show( ResourceStrings.PromptXML2RTF );
            string sourceFileName = null;
            string descFileName = null;
            using (OpenFileDialog dlg = new OpenFileDialog())
            {
                dlg.Filter = "XML文件|*.xml";
                dlg.CheckFileExists = true;
                dlg.ShowReadOnly = false;
                dlg.Title = ResourceStrings.SOURCEXMLDLGTITLE ;
                if (dlg.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
                {
                    sourceFileName = dlg.FileName;
                }
                else
                {
                    return;
                }
            }
            using (SaveFileDialog dlg = new SaveFileDialog())
            {
                dlg.Filter = "RTF文件(*.rtf)|*.rtf";
                dlg.CheckPathExists = true;
                dlg.OverwritePrompt = true;
                if (dlg.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
                {
                    descFileName = dlg.FileName;
                }
                else
                {
                    return;
                }
            }

            XTextDocument document = new XTextDocument();
            document.Load(sourceFileName, FileFormat.XML);
            using (System.Drawing.Graphics g = document.CreateGraphics())
            {
                document.RefreshSize(g);
                document.ExecuteLayout();
                document.RefreshPages();
                document.Save(descFileName, FileFormat.RTF);
            }
            MessageBox.Show( string.Format( ResourceStrings.SUCCESSXML2RTF_SOURCE_DESC , sourceFileName , descFileName ));
        }

        /// <summary>
        /// 文档内容发生改变事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void myEditControl_DocumentContentChanged(object sender, EventArgs e)
        {
            //System.Console.WriteLine("");
            //System.Diagnostics.Debug.WriteLine(
            //    System.Environment.TickCount + ":" + myEditControl.DocumentContentVersion);
            XTextInputFieldElement field = myEditControl.Document.CurrentField as XTextInputFieldElement;

        }

        private void mTestSetInputFieldText_Click(object sender, EventArgs e)
        {
            XTextInputFieldElement field = (XTextInputFieldElement ) myEditControl.GetCurrentElement(
                typeof(XTextInputFieldElement));
            if (field != null)
            {
                // 直接设置文本输入域的内容
                field.EditorTextExt = DateTime.Now.ToString();
            }
        }

        private void mTestInsertCheckBoxList_Click(object sender, EventArgs e)
        {
            myEditControl.ExecuteCommand("InsertCheckBoxList", true, null);

            //myEditControl.Document.GetSpecifyElements(typeof(XTextCheckBoxElement));
        }

        private void mTestSetStyle_Click(object sender, EventArgs e)
        {
            XTextInputFieldElement field = ( XTextInputFieldElement ) myEditControl.Document.GetCurrentElement(typeof(XTextInputFieldElement));
            if (field != null)
            {
                using (FontDialog dlg = new FontDialog())
                {
                    dlg.Font = field.RuntimeStyle.Font.Value;
                    dlg.Color = field.RuntimeStyle.Color;
                    dlg.ShowColor = true;
                    if (dlg.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
                    {
                        DocumentContentStyle newStyle = new DocumentContentStyle();
                        newStyle.DisableDefaultValue = true;
                        newStyle.Font = new XFontValue(dlg.Font);
                        newStyle.Color = dlg.Color;
                        //newStyle.BackgroundColor = Color.Yellow;
                        field.EditorSetContentStyle(newStyle, true);
                        //field.EditorText = "";
                        //field.EditorText = DateTime.Now.ToString();
                    }
                }
            }
        }

        private void mTestChangeEditorTextExt_Click(object sender, EventArgs e)
        {
            XTextInputFieldElement field = (XTextInputFieldElement)myEditControl.GetCurrentElement(typeof(XTextInputFieldElement));
            if (field != null)
            {
                XTextElementList fields = myEditControl.Document.Fields;
                XTextInputFieldElement nextField = (XTextInputFieldElement)fields.GetNextElement(field);
                if (nextField != null)
                {
                    nextField.EditorTextExt = Guid.NewGuid().ToString();
                }
            }
        }

        private void myEditControl_StatusTextChanged(object sender, EventArgs e)
        {
            lblStatus.Text = myEditControl.StatusText;
            this.statusStrip1.Refresh();
        }

        private void mPermissionConfig_Click(object sender, EventArgs e)
        {
            using (dlgPermissionConfig dlg = new dlgPermissionConfig())
            {
                dlg.Document = this.myEditControl.Document;
                if (dlg.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
                {
                    myEditControl.RefreshDocument();
                }
            }
        }

        private void mLogin_Click(object sender, EventArgs e)
        {
            using (dlgLogin dlg = new dlgLogin())
            {
                dlg.LoginInfo = new UserLoginInfo();
                if (dlg.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
                {
                    myEditControl.UserLogin(dlg.LoginInfo , true );
                }
            }
        }

        /// <summary>
        /// 编辑器中执行命令时的错误处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private void myEditControl_CommandError(object sender, CommandErrorEventArgs args)
        {
            MessageBox.Show(
                this,
                args.CommandName + "\r\n" + args.Exception.ToString(), 
                this.Text,
                MessageBoxButtons.OK,
                MessageBoxIcon.Exclamation);

        }


        

    }
}
